package com.example.springboot.controller;

import com.example.springboot.bean.Employee;
import com.example.springboot.config.mysql.DataSourceContext;
import com.example.springboot.config.mysql.UseDataSource;
import com.example.springboot.service.EmployeeService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 数据源的切换实验
 *
 * @Author:ChenZhangKun
 * @Date: 2020/11/1 16:16
 */
@RestController
@RequestMapping("/mysql")
@EnableAspectJAutoProxy(exposeProxy = true)
public class MysqlController {
    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/insertEmp")
    @UseDataSource("master")
    public String insert(Employee employee) {
        // 解决同一类中方法调用动态代理失效的问题
        // 拿到当前类的代理的对象
        // 使用threadLocal绑定的代理对象
        MysqlController o = (MysqlController) AopContext.currentProxy();
        // 根据业务选择使用哪个数据库
        // 主从复制原理
        // DataSourceContext.setDataSource("alibaba");
        employeeService.insert(employee);
        // 移除
        DataSourceContext.clearDataSource();
        return "插入成功";
    }
}
